//
//  RWHomePageViewController.m
//  RedWine
//
//  Created by Liufangfang on 2016/12/26.
//  Copyright © 2016年 HuiBangKe. All rights reserved.
//

#import "RWHomePageViewController.h"
#import "FTYMenuViewController.h"
#import "RWHomePageCollectionViewCell.h"
#import "SegmentSuperViewController.h"
#import "RWMessageViewController.h"
#import "FTYCollectionPort.h"
#import "MJRefresh.h"

#import "RWGoodsModel.h"

#define RW_PAGE_SIZE 10

@interface RWHomePageViewController ()<RWHomePageCollectionViewCellDelegate>

@property (nonatomic, strong) FTYMenuViewController *menuVC;

@property (nonatomic, copy) NSMutableArray *goodsModels;
@property (nonatomic, copy) RWGoodsModel *goodsModel;

@end

static NSString *cellID = @"homePageCellID";

@implementation RWHomePageViewController

#pragma mark - View LifeCycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initObjects];
    //[self loadDatas];
    [self configNotification];
    [self setHomePageUI];
    [self setMJRefreshUI];
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //每次进来都刷新列表数据
    [self loadNewData];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Load Datas

- (void)initObjects{

    _goodsModels = [NSMutableArray array];
    _goodsModel = [[RWGoodsModel alloc] init];
}
- (void)loadDatas{
    
    if (_homePageCV) {
        [_homePageCV removeFromSuperview];
    }

    [FTYHTTPManager postInfoWithSubUrl:[NSString stringWithFormat:@"/shop/ybkapi.php?act=ybkapi&op=goodslist&class=%@&sp_value_id=%@&member_id=%@", _fromFlag, _fromID, [FTYUser sharedUser].userID] parameters:nil block:^(id result, NSError *error) {
        if (!error) {
            
            DLog(@"首页=====================%@", result);
            
            FTYBaseModel *baseModel = [[FTYBaseModel alloc] init];
            baseModel = [FTYBaseModel mj_objectWithKeyValues:result];
            FTYErrorInfoModel *errorInfo = [FTYErrorInfoModel mj_objectWithKeyValues:baseModel.err];
            
            if (0 == errorInfo.errorcode) {
                
                [_goodsModels addObjectsFromArray:[FTYBaseModel mj_objectWithKeyValues:result].info];
                
                [self setHomePageUI];
                [self setMJRefreshUI];
            } else {
                [[FTYToastView alloc] addTitle:errorInfo.errorinfo addView:self.view];
            }
        } else {
            
            NSLog(@"商品列表界面请求错误：%@", error);
        }
    }];
}
//刷新数据
- (void)loadNewData
{
   
    __weak UICollectionView *tableView = self.homePageCV;
   
    
    [FTYHTTPManager postInfoWithSubUrl:[NSString stringWithFormat:@"/shop/ybkapi.php?act=ybkapi&op=goodslist&class=%@&sp_value_id=%@&member_id=%@", _fromFlag, _fromID, [FTYUser sharedUser].userID] parameters:nil block:^(id result, NSError *error) {
        if (!error) {
            
            DLog(@"首页=====================%@", result);
            
            FTYBaseModel *baseModel = [[FTYBaseModel alloc] init];
            baseModel = [FTYBaseModel mj_objectWithKeyValues:result];
            FTYErrorInfoModel *errorInfo = [FTYErrorInfoModel mj_objectWithKeyValues:baseModel.err];
            
            if (0 == errorInfo.errorcode) {
                
                [_goodsModels removeAllObjects];
                [_goodsModels addObjectsFromArray:[FTYBaseModel mj_objectWithKeyValues:result].info];
                [tableView reloadData];
            } else {
                [[FTYToastView alloc] addTitle:errorInfo.errorinfo addView:self.view];
            }
        } else {
            
            NSLog(@"商品列表界面请求错误：%@", error);
        }
        
        [tableView.mj_header endRefreshing];
    }];
    
}

//加载更多数据
- (void)loadMoreData
{
    
    __weak UICollectionView *tableView = self.homePageCV;
    
    
    NSInteger kPagesize = 10;
    NSInteger kPagenum = [_goodsModels count]/kPagesize + 1;
    
    [FTYHTTPManager postInfoWithSubUrl:[NSString stringWithFormat:@"/shop/ybkapi.php?act=ybkapi&op=goodslist&class=%@&sp_value_id=%@&goods_page=%ld&goods_limit=%ld&member_id=%@", _fromFlag, _fromID,kPagenum,kPagesize, [FTYUser sharedUser].userID] parameters:nil block:^(id result, NSError *error) {
        if (!error) {
            
            DLog(@"首页=====================%@", result);
            
            FTYBaseModel *baseModel = [[FTYBaseModel alloc] init];
            baseModel = [FTYBaseModel mj_objectWithKeyValues:result];
            FTYErrorInfoModel *errorInfo = [FTYErrorInfoModel mj_objectWithKeyValues:baseModel.err];
            
            if (0 == errorInfo.errorcode) {
                
                [_goodsModels addObjectsFromArray:[FTYBaseModel mj_objectWithKeyValues:result].info];
                
                [_homePageCV reloadData];
                
            } else {
                [[FTYToastView alloc] addTitle:errorInfo.errorinfo addView:self.view];
            }
        } else {
            
            NSLog(@"商品列表界面请求错误：%@", error);
        }
        
        [tableView.mj_footer endRefreshing];
    }];
}

- (void)refreshDatas{

    [_homePageCV reloadData];
}

#pragma mark - Config UI

- (void)setHomePageUI{

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake((FTY_SCREEN_WIDTH - .5*FTY_WIDTH_BASE) / 2, 340.*FTY_WIDTH_BASE);
    flowLayout.minimumInteritemSpacing = 0.*FTY_WIDTH_BASE;
    flowLayout.minimumLineSpacing = .5*FTY_WIDTH_BASE;
    
   // _homePageCV = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, FTY_SCREEN_WIDTH, FTY_SCREEN_HEIGHT - FTY_NAVIGATION_HEIGHT - FTY_TABBAR_HEIGHT - 85*FTY_HEIGHT_BASE) collectionViewLayout:flowLayout];
    _homePageCV = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, FTY_SCREEN_WIDTH, FTY_SCREEN_HEIGHT - FTY_TABBAR_HEIGHT - 85*FTY_HEIGHT_BASE) collectionViewLayout:flowLayout];
    [self.view addSubview:_homePageCV];
    _homePageCV.backgroundColor = [FTYColor getEEEEEEColorWithAlpha:1.];
    _homePageCV.dataSource = self;
    _homePageCV.delegate = self;
    [_homePageCV registerClass:[RWHomePageCollectionViewCell class] forCellWithReuseIdentifier:cellID];
}

- (void)setMJRefreshUI{
    __weak __typeof(self) weakSelf = self;
    
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.homePageCV.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf loadNewData];
    }];
    
    
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.homePageCV.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf loadMoreData];
    }];
}

#pragma mark - Notification Method

- (void)configNotification{

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshDatas) name:@"RefreshLoginSuccessNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadDatas) name:@"CollectionCancelToHomepageNotification" object:nil];
}

#pragma mark - Notificaiton Invoke Method

#pragma mark - Private Invoke Methods

#pragma mark - <UICollectionViewDataSource>

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    return _goodsModels.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    RWHomePageCollectionViewCell *homePageCell = (RWHomePageCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    NSInteger row = indexPath.row;
    if (homePageCell) {
        
        homePageCell.delegate = self;
        //cell的tag值不设置，默认为0
        homePageCell.tag = row;
        [homePageCell loadDataWithModel:_goodsModels[row]];
    }
    return homePageCell;
}

#pragma mark - <UICollectionViewDelegate>

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

    RWGoodsModel *goodsModel = [RWGoodsModel mj_objectWithKeyValues:_goodsModels[indexPath.row]];
    SegmentSuperViewController *detailPageVC = [[SegmentSuperViewController alloc] init];
    detailPageVC.hidesBottomBarWhenPushed = YES;
    detailPageVC.goodsID = goodsModel.goods_id;
    [self.navigationController pushViewController:detailPageVC animated:YES];
}

#pragma mark - <RWHomePageCollectionViewCellDelegate>

- (void)collection:(UIButton *)btn atIndex:(NSInteger)index{

    RWGoodsModel *goodsModel = [RWGoodsModel mj_objectWithKeyValues:_goodsModels[index]];
    
    if (!btn.selected) {
        
        [FTYCollectionPort requestCollectionWithProjectID:goodsModel.goods_id viewController:self block:^(BOOL isBool) {
            goodsModel.is_coll = isBool;
            btn.selected = isBool;
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"CollectionNotification" object:nil];
        }];
    } else {
        
        [FTYCollectionPort requestCancelCollectionWithProjectID:goodsModel.goods_id viewController:self block:^(BOOL isBool) {
            goodsModel.is_coll = isBool;
            btn.selected = isBool;
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"CollectionNotification" object:nil];
        }];
    }
}

- (void)shoppingCart:(UIButton *)btn atIndex:(NSInteger)index{

    RWGoodsModel *goodsModel = [RWGoodsModel mj_objectWithKeyValues:_goodsModels[index]];
//    [FTYShoppingCartPort requestShoppingCartWithProjectID:goodsModel.goods_id viewController:self block:^(BOOL isBool) {
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"AddShopCartNumberNotification" object:nil];
//    }];
    [FTYShoppingCartPort addShoppingCartWithProjectID:goodsModel.goods_id viewController:self block:^(BOOL isBool) {
        
    }];
}

#pragma mark - Private Invoke Methods

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
